package com.nike.main;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.client.config.RequestConfig;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

import cn.hellotrue.HelloTrue;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.nike.bean.NikeName;
import com.nike.bean.NikeWebCookie;
import com.nike.dao.NikeDao;
import com.nike.http.NikeHttpClient;
import com.nike.util.JSUtil;

public class NikeLoginTestThreadMain extends Thread {
	// 版本
	public static String uncoming = "https://www.nike.com/cn/launch/?s=upcoming";
	public static String loginurl = "https://store.nike.com/cn/zh_cn/?l=shop,login_register";
	public static String addressurl = "https://www.nike.com/cn/zh_cn/p/settings";
	// 版本
		public static String indexurl = "https://www.nike.com/cn/zh_cn";
		public static String dataurl = "https://www.nike.com/_bm/_data";
		public static String storedataurl = "https://secure-store.nike.com/_bm/_data";
		
//		public static String loginurl = "https://store.nike.com/cn/zh_cn/?l=shop,login_register";
		public static String settingurl = "https://www.nike.com/cn/zh_cn/p/settings";
		public static String loginUrl = "https://unite.nike.com/login?appVersion=355&experienceVersion=306&uxid=com.nike.commerce.nikedotcom.web&locale=zh_CN&backendEnvironment=identity&browser=Google%20Inc.&os=undefined&mobile=false&native=false&visit=1&visitor=";

		public static String userurl="https://unite.nike.com/getUser?appVersion=355&experienceVersion=306&uxid=com.nike.commerce.nikedotcom.web&locale=zh_CN&backendEnvironment=identity&browser=Google%20Inc.&os=undefined&mobile=false&native=false&visit=1&visitor={visitor}&uuid={uuid}&atgSync=true";
		public static String phoneAndCodeurl = "https://idn.nike.com/idn/phone/";
		public static String addAddressUrl = "https://www.nike.com/profile/services/users/{UUID}/addresses";
		public static String deviceurl = "https://idn.nike.com/plus/devices?access_token={ACCESS_TOKEN}";
		public static String slcheck_cookiesurl = "https://unite.nike.com/auth/slcheck_cookies/v1?appVersion=354&experienceVersion=304&uxid=com.nike.commerce.nikedotcom.web&locale=zh_CN&backendEnvironment=identity&browser=Google%20Inc.&os=undefined&mobile=false&native=false&visit=1&visitor={VISITOR}&atgSync=true&uxId=com.nike.commerce.nikedotcom.web&cookieType=N";
		public static String countTokenurl = "https://api.nike.com/plus/v3/notifications/me/stored/count?access_token={ACCESS_TOKEN}";
		public static String initAppurl = "https://unite.nike.com/appInitialization?appVersion=355&experienceVersion=306&uxid=com.nike.commerce.nikedotcom.web&locale=zh_CN&backendEnvironment=identity&browser=&os=undefined&mobile=false&native=false&visit=&visitor=&clientId=HlHa2Cje3ctlaOqnxvgZXNaAs7T9nAuH&status=success&uxId=com.nike.commerce.nikedotcom.web&isAndroid=false&isIOS=false&isMobile=false&isNative=false&timeElapsed=4627";
		
	private Map<String, Object> zhanghaomap;
	private String ipAndPort;

	public String getIpAndPort() {
		return ipAndPort;
	}

	public void setIpAndPort(String ipAndPort) {
		this.ipAndPort = ipAndPort;
	}

	public Map<String, Object> getZhanghaomap() {
		return zhanghaomap;
	}

	public void setZhanghaomap(Map<String, Object> zhanghaomap) {
		this.zhanghaomap = zhanghaomap;
	}

	public NikeLoginTestThreadMain(Map<String, Object> zhanghaomap, String ipAndPort) {
		super();
		this.zhanghaomap = zhanghaomap;
		this.ipAndPort = ipAndPort;
	}

	@Override
	public void run() {
		WebDriver wd = null;
		try {
			// 查询数据库，得到已发货的订单
			String telphone = "";
			NikeDao dao = new NikeDao();
			System.setProperty("webdriver.chrome.driver",
					"c:\\chromedriver.exe");

			wd = new ChromeDriver();
			String email = zhanghaomap.get("email") + "";
			String pwd = zhanghaomap.get("pwd") + "";
			String lastname = zhanghaomap.get("lastname") + "";
			String firstname = zhanghaomap.get("firstname") + "";
			telphone = zhanghaomap.get("tel") + "";
			System.out.println("电话号码为："+telphone);
			wd.get(loginurl);
			wd.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
			
			Set<Cookie> cooSet = wd.manage().getCookies();
			NikeWebCookie nwc = new NikeWebCookie();
			nwc.setContent(wd.getPageSource());
			for(Cookie cookie : cooSet){
				System.out.println(cookie.getName()+"::::::::"+cookie.getName());
					if(cookie.getName().startsWith("_abck")){
						nwc.set_abck(cookie.getName());
					}else if(cookie.getName().startsWith("ak_bmsc")){
						nwc.setAk_bmsc(cookie.getName());
					}else if(cookie.getName().startsWith("akamai")){
						nwc.setAkamai(cookie.getName());
					}else if(cookie.getName().startsWith("bm_mi")){
						nwc.setBm_mi(cookie.getName());
					}else if(cookie.getName().startsWith("bm_sz")){
						nwc.setBm_sz(cookie.getName());
					}
				}
			//获取到visitor
			//通过协议进行登录
			// 取出_abck
			RequestConfig requestConfig = RequestConfig.custom()
					.setSocketTimeout(60000).setConnectTimeout(60000)
					.setConnectionRequestTimeout(60000)
					.build();
						// 取出client_id
						Pattern p1 = Pattern
								.compile("_abck=(.*); expires=");
						Matcher m1 = p1.matcher(nwc.get_abck());
						String _abck = "";
						while (m1.find()) {
							_abck += m1.group(1);
						}
						System.out.println("_abck ::: "+_abck);
						Pattern p2 = Pattern
								.compile("data-clientid=\"(.*)\"");
						Matcher m2 = p2.matcher(nwc.getContent());
						String client_id = "";
						while (m2.find()) {
							client_id += m2.group(1);
						}
						System.out.println("client_id ::: "+client_id);
						
						String visitor = new JSUtil().generateUUID();
						String sensor_data = new JSUtil().sensor_data(_abck);
						//getGuid("guidS", generateUUID(), 315569200, "/", "nike.com");
					    //getGuid("guidU", _neo.jackin.generateUUID(), 94670856, "/", _neo.jackin.rootDomain())
//						String guidS = new JSUtil().getGuid("guidS", new JSUtil().generateUUID(), "315569200");
//						String guidU = new JSUtil().getGuid("guidU", new JSUtil().generateUUID(), "94670856");
//						System.out.println("guidS:::"+new JSUtil().generateUUID());
//						System.out.println("guidU:::"+new JSUtil().generateUUID());
						
						//---------------------
//						nwc.setGuidS("guidS="+guidS);
//						nwc.setGuidS("guidU="+guidU);
//						nwc.setPpd("ppd=homepage%7Cnikecom%3Ehomepage");
						//--------------------
						NikeHttpClient nhttp = NikeHttpClient.getInstance();
						String success = nhttp.sendHttpPostJson(dataurl,nwc,sensor_data, requestConfig);
						System.out.println("success:::"+success);
						String textdata= "{\"username\":\"{NAME}\",\"password\":\"{PASS}\",\"keepMeLoggedIn\":true,\"client_id\":\"{client_id}\",\"ux_id\":\"com.nike.commerce.nikedotcom.web\",\"grant_type\":\"password\"}";
						textdata=textdata.replace("{NAME}", zhanghaomap.get("email")+"");
						textdata=textdata.replace("{PASS}", "Q"+zhanghaomap.get("pwd")+"");
						textdata=textdata.replace("{client_id}", client_id);
						System.out.println("textdata:::"+textdata);
						
						if(success.contains("true")){
							loginUrl = loginUrl+visitor;
							
							String userStr = nhttp.sendHttpPostText(loginUrl,nwc,textdata, requestConfig);
							//{"username":"{NAME}","password":"{PASS}","keepMeLoggedIn":true,"client_id":"{client_id}","ux_id":"com.nike.commerce.nikedotcom.web","grant_type":"password"}
							System.out.println("userStr:::"+userStr);
							if(userStr.contains("Failed")||userStr.contains("Access Denied")){
								//登录不上，表示未注册
								zhanghaomap.put("registerstatus", "0");
								dao.updateRegisterStatus(zhanghaomap);
								//第一次失败，再重发一次
								sensor_data = new JSUtil().sensor_data(_abck);
								success = nhttp.sendHttpPostJson(dataurl,nwc,sensor_data, requestConfig);
								System.out.println(success);
								userStr = nhttp.sendHttpPostText(loginUrl,nwc,textdata, requestConfig);
								System.out.println("userStr:::"+userStr);
								return;
							}
							JSONObject userobject = JSONObject.parseObject(userStr) ;
							if(userobject.getIntValue("status")==200){
								JSONObject response = (JSONObject)userobject.get("response");
								String access_token = response.getString("access_token");
								String user_id = response.getString("user_id");
								nwc.setAccess_token(access_token);
								if(userStr!=null && !"".equals(userStr)){
									
									userurl = userurl.replace("{visitor}", visitor);
									userurl = userurl.replace("{uuid}", user_id);
									nwc = nhttp.sendHttpsGetPhone(userurl,nwc, requestConfig);
									System.out.println("Content:::"+nwc.getContent());
									//{"entity":{"postalCode":null,"country":"CN","gender":"2","height":0.0,"weight":0.0,"distanceUnit":null,"city":null,"state":null,"countyDistrict":null,"firstName":"正","lastName":"张","dateOfBirth":"1986-07-24","id":"e90d4777-6945-4654-8737-19357c6bf12a","optIns":null,"middleName":null,"locale":"zh_CN","receiveEmail":"1","receiveSms":false,"dataShareOptIns":[{"code":"00001","defaultValue":true}],"account":{"id":"e90d4777-6945-4654-8737-19357c6bf12a","email":"shanyuanqing001@163.com","access":null,"nikePlusId":null,"notComplex":false,"passwordSettings":null,"screenName":"正张760481572","isAutoGenSN":false,"type":"nike","externalUserId":"a1fa0bab151a49df84f96763d82e3d0f"},"registrationSiteId":"nikedotcom","mobileNumber":"+8615568886474","jpLastNameKana":null,"jpFirstNameKana":null,"jpKNumber":null,"cnEducation":null,"cnCareer":null,"cnFavoriteSports":null,"cnIdNum":null,"fuelActivationDate":null,"heightUnit":"FT/INCHES","weightUnit":"POUNDS","avatar":{"base":"","crop":null,"preview":null,"fullUrl":null,"id":"e90d4777-6945-4654-8737-19357c6bf12a","prefix":"https://www.nike.com/vc/profile/","suffix":"_LRG.jpg"},"bio":null,"links":null,"mspFirstName":"正","mspLastName":"张","mspGender":"2","mspDateOfBirth":"1986-07-24","mspEmail":"shanyuanqing001@163.com","mspScreenName":"正张760481572","emailOnly":false,"ofRequiredAge":false,"shoeSize":null,"shoeSizeUnit":null,"shoeInfoUpdatedByApp":null,"registrationDate":null},"links":[],"statusOverview":{"statusIndicator":"success","messages":[],"durationInMS":null}}
									if(nwc.getContent().contains("Failed")){
										for(int i=0;i<5;i++){
											userurl = userurl.replace("{visitor}", visitor);
											userurl = userurl.replace("{uuid}", user_id);
											nwc = nhttp.sendHttpsGetPhone(userurl,nwc, requestConfig);
											System.out.println("Content:::"+nwc.getContent());
											if(nwc.getContent().contains("entity"))break;
										}
									}
									JSONObject userJ = JSONObject.parseObject(nwc.getContent());
									JSONObject entity=  (JSONObject)userJ.get("entity");
									Object mobileNumber = entity.get("mobileNumber");
									Object firstName = entity.get("firstName");
									Object lastName = entity.get("lastName");
									if(zhanghaomap.get("firstname")==null){
										zhanghaomap.put("firstname", firstName);
										zhanghaomap.put("lastname", lastName);
									}
									System.out.println("mobileNumber:::"+mobileNumber);
									
									//增加slcheck_cookiesurl
									slcheck_cookiesurl =slcheck_cookiesurl.replace("{VISITOR}", visitor);
									nwc = nhttp.sendHttpsGetPhone(slcheck_cookiesurl,nwc, requestConfig);
									
									countTokenurl = countTokenurl.replace("{ACCESS_TOKEN}", access_token);
									nhttp.sendHttpsGet(countTokenurl, requestConfig);
									
										if( mobileNumber==null){
											//执行验证手机操作
											HelloTrue ht = new HelloTrue();
											telphone = ht.getPhone_nike(HelloTrue.TOKEN);
											String phoneurl = phoneAndCodeurl+"+86"+telphone;
											nwc = nhttp.sendHttpOption(phoneurl,nwc,requestConfig);
											nwc = nhttp.sendHttpPut(phoneurl,nwc,requestConfig);
											String telCode = ht.getMessage_nike(HelloTrue.TOKEN, telphone);
											System.out.println("获取到的验证码信息为：" + telCode);
											if("超时".equals(telCode)){
												try {
													throw new Exception("未获取到验证码");
												} catch (Exception e) {
												}
											}
											String regEx="[^0-9]";   
											Pattern p = Pattern.compile(regEx);   
											telCode = p.matcher(telCode).replaceAll("").trim().substring(0,6);
											System.out.println("截取后的验证码信息为：" + telCode);
											
											String codeurl = phoneAndCodeurl+telCode;
											nwc = nhttp.sendHttpOption(codeurl,nwc,requestConfig);
											nhttp.sendHttpPostCode(codeurl,nwc,"",requestConfig);
											zhanghaomap.put("tel",telphone);
											dao.updateTelphone(zhanghaomap);
										}else{
											if(zhanghaomap.get("tel")==null){
												zhanghaomap.put("tel",mobileNumber);
												dao.updateTelphone(zhanghaomap);
											}
										}
									//查询地址	
									sensor_data = new JSUtil().sensor_data(nwc.get_abck());
									success = nhttp.sendHttpPostJson(dataurl,nwc,sensor_data, requestConfig);
									System.out.println("success:::"+success);
									//增加访问setting页面
									nwc = nhttp.sendHttpsGetPhone(settingurl, nwc, requestConfig);
									nwc = nhttp.sendHttpsGetPhone("https://idn.nike.com/user/accountsettings", nwc, requestConfig);
									nwc = nhttp.sendHttpsGetPhone("https://idn.nike.com/authbycookie", nwc, requestConfig);
									
									
									addAddressUrl = addAddressUrl.replace("{UUID}", user_id);
									nwc = nhttp.sendHttpsGetPhone(addAddressUrl,nwc, requestConfig);
									System.out.println("Content:::"+nwc.getContent());
									//{"entity":{"postalCode":null,"country":"CN","gender":"2","height":0.0,"weight":0.0,"distanceUnit":null,"city":null,"state":null,"countyDistrict":null,"firstName":"正","lastName":"张","dateOfBirth":"1986-07-24","id":"e90d4777-6945-4654-8737-19357c6bf12a","optIns":null,"middleName":null,"locale":"zh_CN","receiveEmail":"1","receiveSms":false,"dataShareOptIns":[{"code":"00001","defaultValue":true}],"account":{"id":"e90d4777-6945-4654-8737-19357c6bf12a","email":"shanyuanqing001@163.com","access":null,"nikePlusId":null,"notComplex":false,"passwordSettings":null,"screenName":"正张760481572","isAutoGenSN":false,"type":"nike","externalUserId":"a1fa0bab151a49df84f96763d82e3d0f"},"registrationSiteId":"nikedotcom","mobileNumber":"+8615568886474","jpLastNameKana":null,"jpFirstNameKana":null,"jpKNumber":null,"cnEducation":null,"cnCareer":null,"cnFavoriteSports":null,"cnIdNum":null,"fuelActivationDate":null,"heightUnit":"FT/INCHES","weightUnit":"POUNDS","avatar":{"base":"","crop":null,"preview":null,"fullUrl":null,"id":"e90d4777-6945-4654-8737-19357c6bf12a","prefix":"https://www.nike.com/vc/profile/","suffix":"_LRG.jpg"},"bio":null,"links":null,"mspFirstName":"正","mspLastName":"张","mspGender":"2","mspDateOfBirth":"1986-07-24","mspEmail":"shanyuanqing001@163.com","mspScreenName":"正张760481572","emailOnly":false,"ofRequiredAge":false,"shoeSize":null,"shoeSizeUnit":null,"shoeInfoUpdatedByApp":null,"registrationDate":null},"links":[],"statusOverview":{"statusIndicator":"success","messages":[],"durationInMS":null}}
									JSONObject addressJ = JSONObject.parseObject(nwc.getContent());
									JSONArray entityArr=  addressJ.getJSONArray("entity");
									if(entityArr==null || entityArr.size()==0){
										//增加地址
										//增加
										//access_token
										deviceurl = deviceurl.replace("{ACCESS_TOKEN}", access_token);
										nwc = nhttp.sendHttpsGetPhone(deviceurl, nwc,requestConfig);
										//{"additionalPhoneNumber":"","address1":"岔河镇随便路吧19号","address2":"","address3":"","city":"滁州市","country":"CN","firstName":"星","id":null,"lastName":"流","otherName":null,"phoneNumber":"15787832345","postalCode":"669660","preferred":true,"state":"CN-34","type":"SHIPPING","district":"13663","countyDistrict":"来安县"}
										String address = "{\"additionalPhoneNumber\":\"\",\"address1\":\"{ADDRESS}\",\"address2\":\"\",\"address3\":\"\",\"city\":\"滁州市\",\"country\":\"CN\",\"firstName\":\"{FIRSTNAME}\",\"id\":null,\"lastName\":\"{LASTNAME}\",\"otherName\":null,\"phoneNumber\":\"{TELPHONE}\",\"postalCode\":\"669660\",\"preferred\":true,\"state\":\"CN-34\",\"type\":\"SHIPPING\",\"district\":\"13663\",\"countyDistrict\":\"来安县\"}";
										String addressRandow = "汊河镇" + NikeName.getRoad() + "路"
												+ NikeName.getNum() + "号" + NikeName.getNum() + "室";
										address = address.replace("{ADDRESS}", addressRandow);
										address = address.replace("{FIRSTNAME}", zhanghaomap.get("firstname")+"");
										address = address.replace("{LASTNAME}", zhanghaomap.get("lastname")+"");
										address = address.replace("{TELPHONE}", zhanghaomap.get("tel")+"");
										System.out.println(address);
										String addressnew = nhttp.sendHttpPostAddr(addAddressUrl,nwc,address,requestConfig);
										System.out.println(addressnew);
										
										JSONObject entityJ=  JSONObject.parseObject(addressnew).getJSONObject("entity");
										if(entityJ!=null ){
											String id = entityJ.getString("id");
											if(id!=null && !"".equals(id)){
												//执行数据库操作
												 zhanghaomap.put("province","CN-34");
												 zhanghaomap.put("city","7970");
												 zhanghaomap.put("area","13663");
												 zhanghaomap.put("address","安徽省滁州市来安县"+addressRandow);
												 dao.updateLoginStatus(zhanghaomap);
											}
										}
									}else{
										//直接修改账号地址信息
										//{"entity":[{"id":"45999999994906916","type":"SHIPPING","preferred":true,"otherName":null,"name":null,"address1":"岔河镇随便路吧19号","address2":"","address3":"","city":"滁州市","state":"CN-34","postalCode":"669660","countyDistrict":"来安县","country":"CN","phoneNumber":"15787832345","additionalPhoneNumber":"","firstName":"星","lastName":"流","alternateFirstName":null,"alternateLastName":null}],"links":[],"statusOverview":{"statusIndicator":null,"messages":[],"durationInMS":null}}
										JSONObject jj = entityArr.getJSONObject(0);
										zhanghaomap.put("province","CN-34");
										 zhanghaomap.put("city","7970");
										 zhanghaomap.put("area","13663");
										 zhanghaomap.put("address",jj.getString("address1"));
										 dao.updateLoginStatus(zhanghaomap);
									}
								}
							}else{
								//登录不上，表示未注册
								zhanghaomap.put("registerstatus", "0");
								dao.updateRegisterStatus(zhanghaomap);
							}
						
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
			
			//
			return;
			
			
			// 等待地址添加成功

			// 购买的时候查找 <a> 文字为购买的点击

			// 找li data-size="44" 的点击

			// 找<a> 内容为保存并继续的进行点击

			// 找<a> 内容为提交订单的进行点击

			// 等20秒 ,或者h3 等待付款，或者 前去付款
	}

	public static void exeCmd(String commandStr) {
		// BufferedReader br = null;
		try {
			Runtime.getRuntime().exec(commandStr);
			// br = new BufferedReader(new
			// InputStreamReader(p.getInputStream()));
			// String line = null;
			// StringBuilder sb = new StringBuilder();
			// while ((line = br.readLine()) != null) {
			// sb.append(line + "\n");
			// }
			// System.out.println(sb.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		// finally
		// {
		// if (br != null)
		// {
		// try {
		// br.close();
		// } catch (Exception e) {
		// e.printStackTrace();
		// }
		// }
		// }
	}

	public static void main(String[] args) throws Exception {
		while (true) {
			// 杀掉所有进程,重新启动
			exeCmd("taskkill /F /im chromedriver.exe");
			Thread.sleep(2000);
			exeCmd("taskkill /F /im chrome.exe");
			Thread.sleep(2000);
			// 重启进程
			NikeDao dao = new NikeDao();
			List<Map<String, Object>> list = dao.getAllZhanghaoLogin();
//			JSONObject jObject = IPFactory
//					.getKdByUrl(IPFactory.ZM_IP_HTTPS_URL_200);
//			JSONArray jArray = jObject.getJSONArray("proxy");
			if (list != null && list.size() > 0) {
				for (int i = 0; i < list.size(); i++) {
					Map<String, Object> zhanghaomap = list.get(i);
//					JSONObject jj = (JSONObject) jArray.get(i);
//					String ipAndPort = jj.getString("ip") + ":"
//							+ jj.getString("port");
					String ipAndPort =  "";
					NikeLoginTestThreadMain xt = new NikeLoginTestThreadMain(
							zhanghaomap, ipAndPort);
					xt.start();
				}
			}
			Thread.sleep(180000);
		}
	}
}
